<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="80%">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm"
             @keyup.enter.native="dataFormSubmit()" label-width="120px">
      <div>
        <el-row>
          <el-form-item class="int" label="商品名称" prop="name">
            <el-input v-model="dataForm.name" placeholder="商品名称"></el-input>
          </el-form-item>
          <el-form-item class="int" label="商品编号" prop="code">
            <el-input v-model="dataForm.code" placeholder="商品编号"></el-input>
          </el-form-item>
          <el-form-item class="int" label="计量单位" prop="measurementName">
            <!--              <el-input v-model="dataForm.measurementId" placeholder="计量单位"></el-input>-->
            <el-autocomplete v-model="dataForm.measurementName" style="width: 100%"
                             :fetch-suggestions="querySearchMeasurement" placeholder="请输入单位名称"
                             popper-class="select-option"
                             @select="handleMeasurementSelect"></el-autocomplete>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item class="int" label="最小面积" prop="minSquares">
            <!--              <el-input v-model="dataForm.minSquares" placeholder="最小面积"-->
            <!--                        oninput = "value=value.replace(/[^\d.]/g,'')"></el-input>-->
            <el-input-number v-model="dataForm.minSquares" controls-position="right" style="width: 100%"
                             :precision="2" :step="0.1" :min="0"></el-input-number>
          </el-form-item>
          <el-form-item class="int" label="单价" prop="unitPrice">
            <!--              <el-input v-model="dataForm.unitPrice" placeholder="单价"-->
            <!--                        oninput = "value=value.replace(/[^\d.]/g,'')"></el-input>-->
            <el-input-number v-model="dataForm.unitPrice" controls-position="right" style="width: 100%"
                             :precision="2" :step="0.1" :min="0"></el-input-number>
          </el-form-item>
          <el-form-item class="int" label="备注" prop="remark">
            <el-input v-model="dataForm.remark" placeholder="备注"></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item class="int" label="生产名称" prop="productName">
            <el-input v-model="dataForm.productName" placeholder="生产名称"></el-input>
          </el-form-item>
          <el-form-item class="int" label="工艺名称" prop="crafts">
            <el-input v-model="dataForm.crafts" placeholder="工艺名称"></el-input>
          </el-form-item>
          <el-form-item class="int" label="工艺单价" prop="craftsPrice">
            <!--              <el-input v-model="dataForm.craftsPrice" placeholder="工艺单价"></el-input>-->

            <el-input-number v-model="dataForm.craftsPrice" controls-position="right" style="width: 100%"
                             :precision="2" :step="0.1" :min="0"></el-input-number>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item>
            <el-button v-if="isAuth('sales:orderdetail:save')" type="primary" @click="addRow">添加</el-button>
            <el-button v-if="isAuth('sales:orderdetail:delete')" type="danger" @click="deleteHandle()"
                       :disabled="dataListSelections.length <= 0">批量删除
            </el-button>
          </el-form-item>
        </el-row>
        <el-form>
          <el-table
            :data="dataList"
            border
            v-loading="dataListLoading"
            @selection-change="selectionChangeHandle"
            style="width: 100%;">
            <el-table-column
              prop="productNameLast"
              header-align="center"
              align="center"
              label="生产名称后缀">
              <template slot-scope="scope">
                <el-input v-model="scope.row.productNameLast"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="min"
              header-align="center"
              align="center"
              label="最小值">
              <template slot-scope="scope">
                <el-input v-model="scope.row.minNum"
                          @keyup.native="scope.row.minNum = oninput(scope.row.minNum)"
                          @input="checkNum(scope.row)"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="max"
              header-align="center"
              align="center"
              label="最大值">
              <template slot-scope="scope">
                <el-input v-model="scope.row.maxNum"
                          @keyup.native="scope.row.maxNum = oninput(scope.row.maxNum)"
                          @blur="checkNum(scope.row)"></el-input>
              </template>
            </el-table-column>
<!--            <el-table-column-->
<!--              prop="rangeNum"-->
<!--              header-align="center"-->
<!--              align="center"-->
<!--              label="范围">-->
<!--              <template slot-scope="scope">-->
<!--                <span v-model="scope.row.rangeNum"></span>-->
<!--              </template>-->
<!--            </el-table-column>-->
            <el-table-column
              fixed="right"
              header-align="center"
              align="center"
              width="150"
              label="操作">
              <template slot-scope="scope">
                <el-button class="el-icon-delete" type="danger"
                           size="small" circle @click.native.prevent="deleteRow(scope.$index, dataList)"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        visible: false,
        infoVal: '1', // 默认展开第一个
        dataList: [],
        delList: [],
        dataForm: {
          commodityId: 0,
          id: 0,
          name: '',
          code: '',
          measurementId: '',
          measurementName: '',
          measurementCode: '',
          crafts: '',
          craftsPrice: '',
          totalCraftsPrice: '',
          productName: '',
          remark: '',
          unitPrice: '',
          minSquares: 0,
          productNameLast: '',
          minNum: '',
          maxNum: '',
          rangeNum: ''

        },
        formDto: {
          productNameList: [],
          deleteProductNameList: []
        },
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        dataRule: {
          name: [
            {required: true, message: '商品名称不能为空', trigger: 'blur'}
          ],
          // code: [
          //   {required: true, message: '商品编号不能为空', trigger: 'blur'}
          // ],
          // cotogaryId: [
          //   {required: true, message: '种类ID不能为空', trigger: 'blur'}
          // ],
          // remark: [
          //   {required: true, message: '备注不能为空', trigger: 'blur'}
          // ],
          unitPrice: [
            {required: true, message: '单价不能为空', trigger: 'blur'}
          ]
        }
      }
    },
    activated () {
      this.getDataListByCommodityId(this.dataForm.headerId)
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/sto/commodity/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.name = data.commodity.name
                this.dataForm.code = data.commodity.code
                this.dataForm.measurementId = data.commodity.measurementId
                this.dataForm.measurementName = data.commodity.measurementName
                this.dataForm.squares = data.commodity.squares
                this.dataForm.crafts = data.commodity.crafts
                this.dataForm.craftsPrice = data.commodity.craftsPrice
                this.dataForm.remark = data.commodity.remark
                this.dataForm.unitPrice = data.commodity.unitPrice
                this.dataForm.minSquares = data.commodity.minSquares
                this.dataForm.crafts = data.commodity.crafts
                this.dataForm.craftsPrice = data.commodity.craftsPrice
                this.dataForm.productName = data.commodity.productName

                this.getDataListByCommodityId(this.dataForm.id)
              }
            })
          } else {
            this.getDataListByCommodityId(0)
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        // 订单明细
        this.formDto.productNameList = this.dataList
        this.formDto.deleteProductNameList = this.delList

        // 检验 取值范围
        if (this.dataList.length > 1) {
          for (let i = this.dataList.length - 1; i > 0; i--) {
            if (Number(this.dataList[i].minNum) <= Number(this.dataList[i - 1].maxNum)) {
              this.$message.error('数值范围不正确')
              return
            }
          }
        }

        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/sto/commodity/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'name': this.dataForm.name,
                'code': this.dataForm.code,
                'measurementId': this.dataForm.measurementId,
                'remark': this.dataForm.remark,
                'unitPrice': this.dataForm.unitPrice,
                'minSquares': this.dataForm.minSquares,
                'crafts': this.dataForm.crafts,
                'craftsPrice': this.dataForm.craftsPrice,
                'productName': this.dataForm.productName,

                'productNameList': this.formDto.productNameList,
                'deleteProductNameList': this.formDto.deleteProductNameList
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      // 计量单位 远程搜索
      // queryString 为在框中输入的值
      // callback 回调函数,将处理好的数据推回
      querySearchMeasurement (queryString, callback) {
        this.s_girard = queryString === '' || queryString === null ? 'undefined' : queryString
        this.loading = true
        this.$http({
          url: this.$http.adornUrl(`/sto/measurement/listMeasurement/${this.s_girard}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.staffs = data.MeasurementMap.MeasurementNameDtoList
          } else {
            this.staffs = []
          }
        })
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          callback(this.staffs)
        }, 500)
        // callback(this.staffs)
      },
      handleMeasurementSelect (item) {
        console.log(item)
        // do something
        this.dataForm.measurementId = item.measurementId
        this.dataForm.measurementName = item.value
      },
      // 获取数据列表
      getDataListByCommodityId (id) {
        this.dataForm.commodityId = id || 0
        this.dataListLoading = true
        this.delList = []
        this.$http({
          url: this.$http.adornUrl(`/sto/productname/listAllByCommodityId`),
          method: 'get',
          params: this.$http.adornParams({
            'commodityId': id
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.list
          } else {
            this.dataList = []
            this.$message.error(data.msg)
          }
          this.dataListLoading = false
        })
      },
      // 新增一行
      addRow () {
        this.dataList.push({
          productNameLast: '',
          minNum: '',
          maxNum: '',
          rangeNum: 0
        })
      },
      // 删除该行
      deleteRow (index, rows) {
        this.delList.push(rows[index].id)
        rows.splice(index, 1)
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 批量删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/sales/orderdetail/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataListByHeadId(this.dataForm.headerId)
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      oninput (num) {
        let str = num
        let len1 = str.substr(0, 1)
        let len2 = str.substr(1, 1)
        // 如果第一位是0，第二位不是点，就用数字把点替换掉
        if (str.length > 1 && len1 === 0 && len2 !== '.') {
          str = str.substr(1, 1)
        }
        // 第一位不能是.
        if (len1 === '.') {
          str = ''
        }
        // 限制只能输入一个小数点
        if (str.indexOf('.') !== -1) {
          let str_ = str.substr(str.indexOf('.') + 1)
          if (str_.indexOf('.') !== -1) {
            str = str.substr(0, str.indexOf('.') + str_.indexOf('.') + 1)
          }
        }
        // 正则替换
        str = str.replace(/[^\d.]/g, '') // 保留数字和小数点
        // str = str.replace(/\.\d\d\d$/, '') // 小数点后只能输两位
        return str
      },
      // 检测最小值
      checkNum (row) {
        if (row.maxNum === '') { return }

        if (Number(row.maxNum) <= Number(row.minNum)) {
          row.maxNum = ''
          row.minNum = ''
          this.$message.error('数值范围不正确')
        } else {
          row.rangeNum = row.minNum + '-' + row.maxNum
        }
      }
    }
  }
</script>
